<template>
  <el-card class="topic-list" shadow="hover">
    <template #header>
      <div class="card-header">
        <el-icon class="header-icon">
          <List />
        </el-icon>
        <span class="header-title">Topic列表</span>
        <el-badge :value="topics.length" :max="99" class="topic-count">
          <el-button 
            type="primary" 
            :icon="Refresh" 
            size="small"
            @click="refreshTopics"
            :loading="loading"
          >
            刷新
          </el-button>
        </el-badge>
      </div>
    </template>

    <!-- 搜索框 -->
    <el-input
      v-model="searchText"
      placeholder="搜索Topic..."
      :prefix-icon="Search"
      clearable
      class="search-input"
    />

    <!-- Topic列表 -->
    <div class="topic-container">
      <el-empty v-if="filteredTopics.length === 0" description="暂无Topic数据" />
      
      <el-table
        v-else
        :data="filteredTopics"
        stripe
        highlight-current-row
        @row-click="handleRowClick"
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        
        <el-table-column prop="name" label="Topic名称" min-width="200">
          <template #default="{ row }">
            <el-text 
              :class="{ 'selected-topic': selectedTopic && selectedTopic.name === row.name }"
              @click="selectTopic(row)"
            >
              {{ row.name }}
            </el-text>
          </template>
        </el-table-column>

        <el-table-column prop="partition_count" label="分区数" width="80" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small">
              {{ row.partition_count }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="replication_factor" label="副本数" width="80" align="center">
          <template #default="{ row }">
            <el-tag type="warning" size="small">
              {{ row.replication_factor }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="配置" width="100" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              :icon="Setting"
              size="small"
              circle
              @click="showTopicConfig(row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="success"
                :icon="Select"
                size="small"
                @click="selectTopic(row)"
              >
                选择
              </el-button>
              <el-button
                type="info"
                :icon="View"
                size="small"
                @click="showTopicDetail(row)"
              >
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Topic配置对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      :title="`Topic配置: ${currentTopic?.name}`"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-descriptions 
        v-if="currentTopic"
        :column="2"
        border
      >
        <el-descriptions-item label="Topic名称">
          {{ currentTopic.name }}
        </el-descriptions-item>
        <el-descriptions-item label="分区数">
          {{ currentTopic.partition_count }}
        </el-descriptions-item>
        <el-descriptions-item label="副本数">
          {{ currentTopic.replication_factor }}
        </el-descriptions-item>
        <el-descriptions-item label="配置数量">
          {{ Object.keys(currentTopic.configs).length }}
        </el-descriptions-item>
      </el-descriptions>

      <h4 style="margin-top: 20px;">配置详情</h4>
      <el-table
        :data="configTableData"
        stripe
        style="width: 100%"
        max-height="400"
      >
        <el-table-column prop="key" label="配置项" width="200" />
        <el-table-column prop="value" label="值" min-width="300" />
      </el-table>

      <template #footer>
        <el-button @click="configDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- Topic详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`Topic详情: ${currentTopic?.name}`"
      width="70%"
      :close-on-click-modal="false"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="Topic名称">
              {{ currentTopic?.name }}
            </el-descriptions-item>
            <el-descriptions-item label="分区数">
              {{ currentTopic?.partition_count }}
            </el-descriptions-item>
            <el-descriptions-item label="副本数">
              {{ currentTopic?.replication_factor }}
            </el-descriptions-item>
            <el-descriptions-item label="配置数量">
              {{ Object.keys(currentTopic?.configs || {}).length }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="分区信息" name="partitions">
          <el-table
            :data="partitionData"
            stripe
            style="width: 100%"
            v-loading="partitionLoading"
          >
            <el-table-column prop="partition_id" label="分区ID" width="100" />
            <el-table-column prop="leader" label="Leader" width="100" />
            <el-table-column prop="replicas" label="副本节点" min-width="150">
              <template #default="{ row }">
                <el-tag 
                  v-for="replica in row.replicas" 
                  :key="replica"
                  size="small"
                  style="margin-right: 4px;"
                >
                  {{ replica }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="isr" label="ISR节点" min-width="150">
              <template #default="{ row }">
                <el-tag 
                  v-for="isr in row.isr" 
                  :key="isr"
                  type="success"
                  size="small"
                  style="margin-right: 4px;"
                >
                  {{ isr }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { useKafkaStore } from '@/stores/kafka'
import { ElMessage } from 'element-plus'
import { 
  List, Refresh, Search, Setting, Select, View 
} from '@element-plus/icons-vue'

export default {
  name: 'TopicList',
  components: {
    List, Refresh, Search, Setting, Select, View
  },
  props: {
    topics: {
      type: Array,
      default: () => []
    }
  },
  emits: ['topic-selected'],
  setup(props, { emit }) {
    const kafkaStore = useKafkaStore()
    
    // 响应式数据
    const searchText = ref('')
    const selectedTopic = ref(null)
    const loading = ref(false)
    
    // 对话框
    const configDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const currentTopic = ref(null)
    const activeTab = ref('basic')
    
    // 分区数据
    const partitionData = ref([])
    const partitionLoading = ref(false)
    
    // 计算属性
    const filteredTopics = computed(() => {
      if (!searchText.value) return props.topics
      
      return props.topics.filter(topic => 
        topic.name.toLowerCase().includes(searchText.value.toLowerCase())
      )
    })
    
    const configTableData = computed(() => {
      if (!currentTopic.value || !currentTopic.value.configs) return []
      
      return Object.entries(currentTopic.value.configs).map(([key, value]) => ({
        key,
        value
      }))
    })
    
    // 方法
    const refreshTopics = async () => {
      loading.value = true
      try {
        await kafkaStore.getTopics()
        ElMessage.success('Topic列表已刷新')
      } catch (error) {
        ElMessage.error(error.message || '刷新Topic列表失败')
      } finally {
        loading.value = false
      }
    }
    
    const selectTopic = (topic) => {
      selectedTopic.value = topic
      emit('topic-selected', topic)
      ElMessage.success(`已选择Topic: ${topic.name}`)
    }
    
    const handleRowClick = (row) => {
      selectTopic(row)
    }
    
    const showTopicConfig = (topic) => {
      currentTopic.value = topic
      configDialogVisible.value = true
    }
    
    const showTopicDetail = async (topic) => {
      currentTopic.value = topic
      detailDialogVisible.value = true
      activeTab.value = 'basic'
      
      // 加载分区信息
      await loadPartitionData(topic.name)
    }
    
    const loadPartitionData = async (topicName) => {
      partitionLoading.value = true
      try {
        const response = await kafkaStore.getTopicPartitions(topicName)
        if (response.success) {
          partitionData.value = response.data
        }
      } catch (error) {
        console.error('获取分区信息失败:', error)
        ElMessage.error('获取分区信息失败')
      } finally {
        partitionLoading.value = false
      }
    }
    
    // 监听详情对话框的Tab切换
    watch(activeTab, (newTab) => {
      if (newTab === 'partitions' && currentTopic.value) {
        loadPartitionData(currentTopic.value.name)
      }
    })
    
    return {
      searchText,
      selectedTopic,
      loading,
      configDialogVisible,
      detailDialogVisible,
      currentTopic,
      activeTab,
      partitionData,
      partitionLoading,
      filteredTopics,
      configTableData,
      refreshTopics,
      selectTopic,
      handleRowClick,
      showTopicConfig,
      showTopicDetail
    }
  }
}
</script>

<style scoped>
.topic-list {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-icon {
  margin-right: 8px;
  color: #409eff;
}

.header-title {
  font-weight: 600;
  flex: 1;
}

.topic-count {
  margin-left: 12px;
}

.search-input {
  margin-bottom: 16px;
}

.topic-container {
  min-height: 200px;
}

.selected-topic {
  color: #409eff;
  font-weight: 600;
  cursor: pointer;
}

.el-table {
  font-size: 14px;
}

.el-table .el-table__row {
  cursor: pointer;
}

.el-table .el-table__row:hover {
  background-color: #f5f7fa;
}

.el-button-group {
  display: flex;
  gap: 4px;
}

.el-descriptions {
  margin-bottom: 16px;
}

.el-tabs {
  margin-top: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-table-column {
    font-size: 12px;
  }
  
  .el-dialog {
    width: 95% !important;
  }
}
</style> 